package com.zxm.oss.service.impl;

import com.alibaba.fastjson2.JSON;
import com.qiniu.common.QiniuException;
import com.qiniu.http.Response;
import com.qiniu.storage.Configuration;
import com.qiniu.storage.Region;
import com.qiniu.storage.UploadManager;
import com.qiniu.storage.model.DefaultPutRet;
import com.qiniu.util.Auth;
import com.zxm.oss.config.QiniuConfigProperties;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;
import java.util.UUID;

/**
 * 七牛云上传策略
 *
 * @author silencezheng
 * @date 2022/07/28
 */
@Service("qiniuUploadStrategyImpl")
public class QiniuUploadStrategyImpl extends AbstractUploadStrategyImpl {
	private final Logger logger = LoggerFactory.getLogger(this.getClass());
	@Autowired
	private QiniuConfigProperties qiniuConfigProperties;
	@Override
	public Boolean exists(String filePath) {
		return true;
	}

	@Override
	public void upload(String path, String fileName, InputStream inputStream) {

	}

	@Override
	public String getFileAccessUrl(String filePath) {
		System.out.println(qiniuConfigProperties.getUrl() + filePath);
		return qiniuConfigProperties.getUrl() + filePath;
	}

	@Override
	public String saveFile(MultipartFile uploadFile) {
		Configuration cfg = new Configuration(Region.huanan());
		UploadManager uploadManager = new UploadManager(cfg);
		String fileName = uploadFile.getOriginalFilename();
		String key = UUID.randomUUID() + fileName.substring(fileName.lastIndexOf("."));
		Auth auth = Auth.create(qiniuConfigProperties.getAccessKey(), qiniuConfigProperties.getSecretKey());
		String upToken = auth.uploadToken(qiniuConfigProperties.getBucket());
		try {
			Response response = uploadManager.put(uploadFile.getBytes(), key, upToken);
			DefaultPutRet putRet = JSON.parseObject(response.bodyString(), DefaultPutRet.class);
			return qiniuConfigProperties.getUrl() + putRet.key;
		} catch (QiniuException e) {
			logger.error("上传文件失败", e);
			logger.error(JSON.toJSONString(e.response));
		} catch (IOException e) {
			logger.error("上传文件失败", e);
		}
		return null;
	}
}
